package com.semidata.rtd.core.job;

import java.util.LinkedList;
import java.util.Queue;

public class SequenceTaskScheduler implements TaskScheduler {

    private Queue<Task<?>> queue;
    private Task<?> current;
    private boolean isCancelled;
    private JobCompleteHandler handler;

    public SequenceTaskScheduler() {
        this.queue = new LinkedList<>();
        this.current = null;
        this.isCancelled = false;
        this.handler = null;
    }

    public void addTask(Task<?> task) {
        queue.add(task);
    }

    @Override
    public synchronized void schedule() {
        if (isCancelled)
            return;
        current = queue.poll();
        if (current == null) {
            if (handler != null)
                handler.handle(null);
            return;
        }

        current.submit();
    }

    @Override
    public synchronized void cancel() {
        isCancelled = true;
        if (current != null)
            current.cancel();
    }

    @Override
    public void setError(Throwable cause) {
        if (handler != null)
            handler.handle(cause);
    }

    @Override
    public void setJobCompleteHandler(JobCompleteHandler handler) {
        this.handler = handler;
    }

}
